﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Caching;
using XQ.Framework.core;

namespace XQ.Framework.cache
{
    /// <summary>
    /// CacheManager 的摘要说明
    /// </summary>
    public class CacheManager
    {
        #region Add Cache
        public static bool AddCache(HttpContext context, string key, object value)
        {
            return CacheManager.AddCache(context, key, value, DateTime.Now.AddMinutes(3));
        }

        public static bool AddCache(HttpContext context, string key, object value, DateTime timeout)
        {
            return CacheManager.AddCache(context, key, value, timeout, null);
        }

        public static bool AddCache(HttpContext context, string key, object value, DateTime timeout,
            System.Web.Caching.CacheDependency dependency)
        {
            try
            {
                context.Cache.Insert(key, value, dependency, timeout, System.Web.Caching.Cache.NoSlidingExpiration);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
        #endregion

        #region Get Cache
        public static T GetCache<T>(HttpContext context, string key)
        {
            try
            {
                object obj = CacheManager.GetCacheObject(context, key);
                return obj == null ? default(T) : (T)obj;
            }
            catch (Exception e)
            {
                return default(T);
            }
        }
        public static object GetCacheObject(HttpContext context, string key)
        {
            try
            {
                return context.Cache.Get(key);
            }
            catch (Exception e)
            {
                return null;
            }
        }
        #endregion

        #region Delete Cache
        public static bool RemoveCache(HttpContext context, params string[] keys)
        {
            try
            {
                if (ValidateHelper.IsPlumpArray<string>(keys))
                {
                    keys.ToList().ForEach(delegate(string key)
                    {
                        context.Cache.Remove(key);
                    });
                }
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
        public static bool ClearCache(HttpContext context)
        {
            try
            {
                IDictionaryEnumerator cache_enum = context.Cache.GetEnumerator();
                while (cache_enum.MoveNext() && cache_enum.Key != null)
                {
                    context.Cache.Remove(cache_enum.Key.ToString());
                }
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
        #endregion

    }
}